<?php
	/**
	 * Implementation of a very generic output component.
	 *
	 * A very basic component for outputting information.	 
	 *
	 * @author     Brandon R. Stoner <brandon.stoner@gmail.com>
	 * @copyright  Copyright 2008, Monokromatic Inc.
	 * @package    Components
	 * @subpackage Output	 
	 **/

	/**
	 * A very generic output component.
	 *
	 * Implements the functionality for outputting information to stdout.	 	 
	 *	 
	 * @author     Brandon R. Stoner <brandon.stoner@gmail.com>
	 * @copyright  Copyright 2008, Monokromatic Inc.
	 * @package    Components
	 * @subpackage Output
	 **/	 	
	class CKromeOutputComponent extends IKromeComponent
	{
		/**
		 * Friendly name for this object.
		 * @var string
		 **/
		public  $name = 'Krome Generic Output Component';
		/**
		 * Descriptor for access to stdout.
		 * @var integer
		 **/
		private $fileDescriptor;

		/**
		 * If we have access to stdout, let the component manager know that this
		 * object is able to utilize it.
		 **/
		public function Register()
		{
			if ( KROME_CLI )
			{
				if ( $this->fileDescriptor = fopen('php://stdout', 'w') )
				{
					$this->RegisterAbility( 'stdout' );
				}
			}
		}

		/**
		 * Close our file descriptor, now that we are done writing to it.
		 **/
		public function Cleanup()
		{
			if ( $this->fileDescriptor )
			{
				fclose( $this->fileDescriptor );
			}
		}

		/**
		 * Writes a message to stdout's buffer. Appends a newline if $endl is true.
		 *
		 * @param string $message The message that should be appended to stdout
		 * @param bool   $endl    True if a line feed should be appended to $message
		 * 
		 * @return bool True if the message was successfully written to the buffer
		 **/
		public function Write( $message, $endl=false )
		{
			$retVal = false;

			if ($endl === true)
			{
				$message = $message . "\n";
			}

			if ( $this->fileDescriptor )
			{
					// If fwrite returns false, it didn't write the data successfully.
				if ( fwrite( $this->fileDescriptor, $message ) !== false )
				{
					$retVal = true;
				}
			}
			else
			{
				print $message;
	
				$retVal = true;
			}

			return $retVal;
		}
	}
?>
